package search;

import java.util.ArrayList;
import java.util.logging.Logger;

import com.google.appengine.api.search.Index;
import com.google.appengine.api.search.IndexSpec;
import com.google.appengine.api.search.Query;
import com.google.appengine.api.search.QueryOptions;
import com.google.appengine.api.search.Results;
import com.google.appengine.api.search.ScoredDocument;
import com.google.appengine.api.search.SearchServiceFactory;

import entities.User;

public class UserSearchData {
	private static Index INDEX = SearchServiceFactory.getSearchService().getIndex(IndexSpec.newBuilder().setName("gea001"));
	
	private static final Logger log = Logger.getLogger(UserSearchData.class.getName());
	
	public static ArrayList<User> searchName(String name) {
		ArrayList<User> users = new ArrayList<User>();
		try {
			StringBuilder queryString = new StringBuilder();
			queryString.append("name: " + name);
			Query query = Query.newBuilder().setOptions(QueryOptions.newBuilder().build()).build(queryString.toString());
			Results<ScoredDocument> docResult = INDEX.search(query);
			if (docResult.getNumberFound() > 0) {
				for (ScoredDocument scoredDocument : docResult) {
					users.add(UserSearchEngine.documentToObjectByReflection(scoredDocument));
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return users;
	}
	
	public static ArrayList<User> searchUsername(String username) {
		ArrayList<User> users = new ArrayList<User>();
		
		try {
			StringBuilder queryString = new StringBuilder();
			queryString.append("username: " + username);
			Query query = Query.newBuilder().setOptions(QueryOptions.newBuilder().build()).build(queryString.toString());
			Results<ScoredDocument> docResults = INDEX.search(query);
			if (docResults.getNumberFound() > 0) {
				for(ScoredDocument sroredDocument : docResults) {
					users.add(UserSearchEngine.documentToObjectByReflection(sroredDocument));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return users;
	}
}
